const User = require("../../model/user/user")
const Role = require("../../model/user/role")
const { Op } = require("sequelize")
const jwt = require("jsonwebtoken")
const config = require("../../config")
const Rule = require("../../model/user/rule")
const { getTime } = require("../../utils/gettime")
const { nanoid } = require("nanoid")

// const {get} = require("../utils/operation")


// 登录
exports.doLogin = async ({ username, password }) => {
    try {
        if (!username && !password) return { msg: "请输入账号或密码", code: "400" }
        const userData = await User.findOne({
            attributes: ["password", "username"],
            where: { username }
        })
        if (userData) {
            let newPassword = jwt.verify(userData.password, config.jwt.secret)
            let token = jwt.sign(userData.username, config.jwt.secret) + "@" + userData.password + nanoid()
            if (newPassword === password) {
                const res = await User.findOne({
                    attributes: ["username", "id", "sex", "phone", "mail", "effect", "status", "avatar", "role_id", "role", "islogin"],
                    where: { username },
                    include: [{
                        model: Role,
                        attributes: ["rolename", "rolekey", "creator", "id"]
                    }]
                })
                if (res) return { msg: "登陆成功", code: "200", data: res, token }
                return { msg: "登陆失败", code: "400" }
            } else {
                return { msg: "登陆失败", code: "400" }
            }
        } else {
            return { msg: "登陆失败", code: "400" }
        }
    } catch (err) { return { msg: "登陆失败", code: "400", err } }
}

// 登出
exports.doLogout = async ({ username, password }) => {
    try {
        if (!username && !password) return { msg: "操作失败 username or password is undefind", code: "400" }
        let islog = await User.findOne({ where: { username } })
        if (!islog.islogin) return { msg: "操作失败 此帐号尚未登录", code: "400" }
        let res = await User.update({ islogin: false }, { where: { username } })
        if (res) return { msg: "操作成功", code: "200" }
        return { msg: "操作失败 账号或密码错误", code: "400" }
    } catch (err) { return { msg: "操作失败", code: "400", err } }
}

// 注册
exports.createUser = async ({ username, password, creator, role_id }) => {
    try {
        username = username.trim()
        password = password.trim()
        if (!username && !password && !role_id) return { msg: "添加失败 数据不完整", code: "400" }
        let findOne = await User.findOne({ where: { username } })
        if (findOne) return { msg: "用户名重复", code: "400" }
        let newData = {}
        newData.username = username;
        if (creator) newData.creator = creator;
        if (role_id) newData.role_id = role_id;
        newData.createdate = getTime()
        let newPassword = jwt.sign(password, config.jwt.secret)
        newData.password = newPassword;
        let create = await User.create(newData)
        if (!create) return { msg: "添加失败", code: "400" }
        let res = await User.findOne({
            attributes: ["username", "sex", "phone", "mail", "effect", "status", "avatar", "role_id", "role", "islogin"],
            where: { username },
            include: [{
                attributes: ["rolename"],
                model: Role,
                include: [{
                    model: Rule,
                    attributes: ["rulename", "summary", "id"]
                }],
            }]
        })
        return { msg: "添加成功", code: "400", data: res }
    } catch (err) { return { msg: "添加失败", code: "400", err } }
}

// 修改用户资料
exports.editUser = async ({ id, sex, phone, mail, effect, status }) => {
    let reg_phone = /^(?:(?:\+|00)86)?1\d{10}$/;
    let reg_mail = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    if (!id) return { msg: "修改失败 ID IS UNDEFIND", code: "400" }
    let newData = {}
    // 传递哪个更新哪个
    if (sex) { newData.sex = sex }
    if (phone) {
        if (reg_phone.test(phone)) {
            newData.phone = phone
        } else {
            return { msg: "请输入正确的手机号", code: "400" }
        }
    }
    if (mail) {
        if (reg_mail.test(mail)) {
            newData.mail = mail
        } else {
            return { msg: "请输入正确的邮箱", code: "400" }
        }
    }
    if (effect) { newData.effect = effect }
    if (status) { newData.status = status }
    newData.update = getTime()
    console.log(newData)
    // 更新
    const res = await User.update(newData, {
        where: { id }
    })
    if (res) {
        const data = await User.findOne({
            attributes: ["username", "sex", "phone", "mail", "effect", "status", "avatar", "update", "updator"],
            where: { id }
        })
        return { msg: "编辑成功", code: "200", data }
    }
    return { msg: "编辑失败", code: "400" }
}

// 获取用户列表
exports.getUserList = async ({ pageNum, pageSize }) => {
    try {
        pageNum = pageNum.replace(/\s*/g, "");
        pageSize = pageSize.replace(/\s*/g, "");
        if (!pageNum && !pageSize) return { msg: "查询失败", code: "400" }
        // exports.getUserList = async () => {
        pageNum = Number(pageNum) || 1
        pageSize = Number(pageSize) || 5
        if (!isNaN(pageNum) && !isNaN(pageSize)) {
            let res = await User.findAndCountAll({
                offset: pageNum * pageSize - pageSize,
                limit: pageSize,
                attributes: ["id", "username", "role_id", "sex", "phone", "mail", "creator", "effect", "status", "avatar"],
                include: [{
                    model: Role,
                    attributes: ["rolename", "rolekey", "creator", "id"],
                    include: [{
                        model: Rule,
                        attributes: ["rulename", "id", "summary"]
                    }]
                }]
            })
            return { msg: "获取成功", code: "200", data: res }
        } else {
            return { msg: "获取失败 pageNum or pageSize is undefind", code: "400" }
        }
    } catch (err) { return { msg: "获取失败", code: "400", err } }
}

// 根据id查询用户
exports.getUser = async ({ id }) => {
    id = Number(id)
    if (!id) return { msg: "查询失败", code: "400" }
    let res = await User.findOne({
        attributes: ["id", "username", "role_id", "sex", "phone", "mail", "creator", "effect", "status", "avatar"],
        where: { id },
        include: [{
            model: Role,
            attributes: ["rolename", "rolekey", "creator", "id"],
            include: [{
                model: Rule,
                attributes: ["rulename", "id", "summary"]
            }]
        }]
    })
    return { msg: "获取成功", code: "200", data: res }
}

// 模糊查询
exports.getUserByName = async ({ name, pageNum, pageSize }) => {
    console.log(name, pageNum, pageSize, "asdfasdd");
    pageNum = Number(pageNum) || 1
    pageSize = Number(pageSize) || 5
    if (!name) return { msg: "查询失败 name is undefind", code: "400" }
    let res = await User.findAndCountAll({
        offset: pageNum * pageSize - pageSize,
        limit: pageSize,
        attributes: ["id", "username", "role_id", "sex", "phone", "mail", "creator", "effect", "status", "avatar", "createdAt"],
        where: {
            username: {
                [Op.like]: `%${name}%`
            }
        },
        include: [{
            model: Role,
            attributes: ["rolename", "rolekey", "creator", "id"],
            include: [{
                model: Rule,
                attributes: ["rulename", "id", "summary"]
            }]
        }]
    })
    return { msg: "获取成功", code: "200", data: res }
}

// 删除用户
exports.remove = async ({ id, updator }) => {
    try {
        if (!id) return { msg: "删除失败 id is undefind", code: "400" }
        let res = await User.update(
            {
                status: true,
                update: getTime(),
                updator
            },
            { where: { id } }
        )
        if (res) return { msg: "删除成功", code: "200" }
        return { msg: "删除失败", code: "400" }
    } catch (err) { return { msg: "删除失败", code: "400", err } }
}